<template>
  <div>
    <div style="width:400px;margin: 150px auto">
      <h1 style="text-align: center;margin-bottom: 30px">登 录</h1>
      <el-form :model="user" size="large" ref="ruleFormRef" :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="user.username" :prefix-icon="User"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="user.password" @keyup.enter="submitForm(ruleFormRef)" :prefix-icon="Lock" show-password/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="submitForm(ruleFormRef)">登 录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref, reactive, onMounted} from "vue";
import {User,Lock} from "@element-plus/icons-vue";
import {ElNotification, FormInstance, FormRules} from "element-plus";
import request from "../../utils/request.js";
import router from "../../router/index.js";

onMounted(()=>{
  let token = sessionStorage.getItem("TOKEN");
  if(token == null){
    ElNotification({
      title: '认证失败',
      type: 'error',
      message: '请先登录！'
    })
  }
})

const ruleFormRef = ref<FormInstance>()

  const user = reactive({
    username: "",
    password: "",
  })

  // 校验
  const rules = reactive<FormRules>({
    username: [
      {required: true, message: '请输入用户名', trigger: 'blur'},
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
    ],
  })

  const submitForm = async (el: FormInstance | undefined) => {
    if (!el) return
    await el.validate((valid, fields) => {

      // 进行校验
      if (valid) {
        // 发送登录请求
        request.post("/login",user).then((res:any) => {
          // 登录成功
          if(res.code == '4624' || res.code == 4624){
            ElNotification({
              title: 'success',
              message: res.msg,
              type: 'success',
            })
            sessionStorage.setItem("TOKEN",JSON.stringify(res.data)) // 部署云服务器后失效
            console.log("登录完之后获取TOKEN：" + sessionStorage.getItem("TOKEN"));
            router.push("/")
          }else {
            ElNotification({
              title: '登录失败',
              message: '用户名或密码校验失败',
              type: 'error',
            })
          }
        })
      } else {
        ElNotification({
          title: 'error',
          message: '用户名或密码校验失败',
          type: 'error',
        })
      }
    })
  }

</script>

<style scoped>

</style>
